package com.iafme.component;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.iafme.dto.req.ExamineReqDTO;
import com.iafme.model.CertificateInfo;
import com.iafme.model.CertificateOrder;
import com.iafme.model.CertificateOrderItem;
import com.iafme.service.CertificateInfoService;
import com.iafme.service.CertificateOrderItemService;
import com.iafme.service.CertificateOrderService;

import com.systemframework.constants.Constants;
import com.systemframework.exception.ResultException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author summer
 * @version 1.0
 * @date 2025/3/27 11:07
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class ExamineService {

    private final CertificateOrderService certificateOrderService;

    private final CertificateOrderItemService itemService;

    private final CertificateInfoService certificateInfoService;

    public void examineOrder(ExamineReqDTO examineReqDTO) {
        CertificateOrder certificateOrder = certificateOrderService.getById(examineReqDTO.getId());
        if(ObjectUtil.isEmpty(certificateOrder)) {
            throw new ResultException("证书订单不存在");
        }
        certificateOrder.setAuthorization(examineReqDTO.getAuthorization1());
        certificateOrder.setExamineText(examineReqDTO.getExamineText());
        certificateOrder.setExamineTime(LocalDateTime.now());
        certificateOrderService.updateById(certificateOrder);
        if(examineReqDTO.getAuthorization1().equals(Constants.TWO)){
            LambdaQueryWrapper<CertificateOrderItem> wrapper = Wrappers.lambdaQuery(CertificateOrderItem.class).eq(CertificateOrderItem::getOrderId, examineReqDTO.getId());
            List<Integer> certificateIds = itemService.list(wrapper).stream().map(CertificateOrderItem::getCertificateId).collect(Collectors.toList());
            List<CertificateInfo> certificateInfoList= ListUtil.list(true);
            certificateIds.forEach(certificateId -> {
                CertificateInfo certificateInfo=new CertificateInfo();
                certificateInfo.setCertificateId(certificateId);
                certificateInfo.setMemberId(certificateOrder.getMemberId());
                certificateInfo.setLevelId(certificateOrder.getLevelId());
                certificateInfo.setProjectId(certificateOrder.getProjectId());
                certificateInfoList.add(certificateInfo);
            });
            certificateInfoService.saveBatch(certificateInfoList);
        }

    }
}
